package main

/* by zy
   - 2025.11.03
  为指定 CDN 域名设置使用的 SSL 证书
  
  -set -fqdn <domain> -cert-di <ID>

*/

import (
  "os"
  "fmt"
  "net/http"
  "encoding/json"
)

type ReqBodySet struct { // PUT /domain/<Name>/httpsconf, Content-Type: application/json
  CertID          string  `json:"certId"`
  ForceHttps      bool    `json:"forceHttps"`
  Http2Enable     bool    `json:"http2Enable"`
}

type RespBodySet struct {
  Code         int    `json:"code"`
  Error        string `json:"error"`
  ErrorCode    string `json:"error_code"`
}

func handleSet(cfg *CLI) {
  var err error
  // 构造请求数据
  jsonData, err := makeSetJSON(cfg)
  if err != nil {
    fmt.Fprintf(os.Stderr, "failed to marshal JSON: %v\n", err)
    os.Exit(ExitMarshalError)
  }
  // 发送请求
  resp, err := sendSetRequest(cfg, jsonData)
  if err != nil {
    fmt.Fprintf(os.Stderr, "failed to send http request: %v\n", err)
    os.Exit(ExitRequestError)
  }
  defer resp.Body.Close()
 
  fmt.Printf("StatusCode: %d\n", resp.StatusCode);
 
  r, err := parseResp[RespBodySet](resp)
  if err != nil {
    fmt.Fprintf(os.Stderr, "failed to parse response: %v\n", err)
    os.Exit(ExitUnmarshalError)
  }

  if resp.StatusCode == 200 {
    fmt.Printf("OK\n")
  } else {
    fmt.Printf("code: %d\nerror: %s\n", r.Code, r.Error);
  }
}

func makeSetJSON(cfg *CLI) ([]byte, error) {
  reqBody := ReqBodySet{
    CertID: cfg.CertID,
    ForceHttps:  false,
    Http2Enable:  true,
  }
  return json.Marshal(&reqBody)
}

func sendSetRequest(cfg *CLI, bodyStr []byte) (*http.Response, error) { // PUT /domain/<Name>/httpsconf, Content-Type: application/json
  return sendQiNiuRequest(cfg, http.MethodPut, "/domain/" + cfg.Fqdn + "/httpsconf", "", bodyStr)
}
